import pytz
from flask import Blueprint,jsonify,request,session,render_template
from sqlalchemy import or_

from exts import db
from models import CartModel,BookInfoModel,BookModel,AddressModel,OrderModel,OrderItemModel,ShouCangModel,CommentModel
from datetime import datetime

bp=Blueprint("product", __name__, url_prefix="/product")

# 购物车页面
@bp.route("/cart")
def cart():
    return render_template("Cart/cart.html")

# 订单确定页面
@bp.route("/confirm")
def confirm():
    cids=request.args.get("cids")
    print(cids)
    return render_template("Cart/orderConfirm.html",cids=cids)

# 订单支付页面
@bp.route("/payment")
def payment():
    price=request.args.get('total_price','')
    print(price)
    return render_template("Cart/payment.html")

# 显示所有订单页面
@bp.route("/showOrder")
def showOrder():
    return render_template("Cart/showOrder.html")

# 收藏页面
@bp.route("/soucang")
def soucang():
    return render_template("Cart/shoucang.html")

# 跳转到搜索显示图书页面
@bp.route("/search")
def search():
    return render_template("Cart/Search.html")

# 图书加入购物车
@bp.route("/add_to_cart",methods=['POST'])
def add_to_cart():
    cid=0
    userid = session.get('user_id')
    data=request.get_json()
    pid=data['pid']
    print("pid:"+pid)
    amount=data['amount']
    goods=CartModel.query.filter_by(uid=userid,pid=pid).first()
    # 此件商品存在于购物车中修改数量
    if goods:
        cnt=goods.num+int(amount)
        goods.num=cnt
        db.session.commit()
    # 添加到购物车中
    else:
        bookinfo=BookInfoModel.query.filter_by(bookid=pid).first()
        price=bookinfo.bookprice
        insertCare=CartModel(uid=userid,pid=pid,price=price,num=amount)
        db.session.add(insertCare)
        db.session.commit()
        cid = insertCare.cid
    return jsonify({'state':'200','data':cid})

# 购物车商品显示界面
@bp.route("/showCart",methods=['GET'])
def showCart():
    userid = session.get('user_id')
    list=[]
    content={}
    goodDetail=db.session.query(CartModel,BookInfoModel,BookModel).join(BookInfoModel,CartModel.pid==BookInfoModel.bookid).join(BookModel,CartModel.pid==BookModel.bookid).filter(CartModel.uid==userid).order_by(CartModel.cid.desc()).all()
    for goodList in goodDetail:
        cart, book,books = goodList
        content={'cid':cart.cid,'uid':cart.uid,'pid':cart.pid,'price':cart.price,'num':cart.num,'bookid':book.bookid,'bookauthor':book.bookauthor,
                 'bookbinfo':book.bookbinfo,'bookdinfo':book.bookdinfo,'bookprice':book.bookprice,
                 'bookname':books.bookname,'booksort':books.booksort}
        list.append(content)
        content={}
    goodDetailList={'state':'200','data':list}
    print(goodDetailList)
    return jsonify(goodDetailList)

# 购物车界面商品数添加
@bp.route("/num/add/<cid>",methods=['POST'])
def numAdd(cid):
    print(cid)
    car=CartModel.query.filter_by(cid=cid).first()
    num=car.num
    car.num=num+1
    db.session.commit()
    return jsonify({'state':'200','data':car.num})

# 购物车界面商品数减少
@bp.route("/num/sub/<cid>",methods=['POST'])
def numSub(cid):
    car = CartModel.query.filter_by(cid=cid).first()
    num = car.num
    car.num = num - 1
    db.session.commit()
    return jsonify({'state': '200', 'data': car.num})

# 删除购物车中单个商品
@bp.route("/delete/<cid>",methods=['POST'])
def deletecart(cid):
    car = CartModel.query.filter_by(cid=cid).first()
    db.session.delete(car)
    db.session.commit()
    return jsonify({'state':'200'})

# 删除购物车中多个商品
@bp.route("/deletes",methods=['POST'])
def deletescart():
    data=request.get_json()
    cids=data['cids']
    lst=list(map(int,cids.split(',')))
    print(cids)
    db.session.query(CartModel).filter(CartModel.cid.in_(lst)).delete()
    db.session.commit()
    return jsonify({'state':'200'})

# 确定页面显示商品信息
@bp.route("/Cart/list/<cids>",methods=['GET'])
def cartlist(cids):
    print(cids)
    userid = session.get('user_id')
    lst = list(map(int, cids.split(',')))
    list1 = []
    content = {}
    goodDetail = db.session.query(CartModel, BookInfoModel, BookModel).join(BookInfoModel,CartModel.pid == BookInfoModel.bookid).join(
        BookModel, CartModel.pid == BookModel.bookid).filter(CartModel.uid == userid,CartModel.cid.in_(lst)).all()
    for goodList in goodDetail:
        cart, book, books = goodList
        content = {'cid': cart.cid, 'uid': cart.uid, 'pid': cart.pid, 'price': cart.price, 'num': cart.num,
                   'bookid': book.bookid, 'bookauthor': book.bookauthor,
                   'bookbinfo': book.bookbinfo, 'bookdinfo': book.bookdinfo, 'bookprice': book.bookprice,
                   'bookname': books.bookname, 'booksort': books.booksort}
        list1.append(content)
        content = {}
    goodDetailList = {'state': '200', 'data': list1}
    print(goodDetailList)
    return jsonify(goodDetailList)

# 确定页面显示地址
@bp.route("/address",methods=['GET'])
def address():
    userid = session.get('user_id')
    addresses = AddressModel.query.filter_by(uid=userid).order_by(AddressModel.is_default.desc()).all()
    content = {}
    list = []
    for address in addresses:
        content = {'aid': address.aid, 'uid': address.uid, 'provinceName': address.province_name,
                   'cityName': address.city_name,
                   'areaName': address.area_name, 'address': address.address, 'phone': address.phone,
                   'tag': address.tag, 'name': address.name}
        list.append(content)
        content = {}
    addressList = {'state': 200, 'data': list}
    print(addressList)
    return jsonify(addressList)

# 创建订单
@bp.route("/order/create/<cids>/<aid>",methods=['POST'])
def ordercreate(cids,aid):
    userid = session.get('user_id')
    lst = list(map(int, cids.split(',')))
    carts=db.session.query(CartModel).filter(CartModel.cid.in_(lst)).all()
    totalprice=0
    for cart in carts:
        totalprice+=cart.price*cart.num
    address=AddressModel.query.filter_by(uid=userid,aid=aid).first()
    # 创建订单
    local_time = datetime.now()
    utc_time = local_time.replace(tzinfo=pytz.timezone('UTC')).astimezone(pytz.UTC)
    new_order=OrderModel(uid=userid,recv_name=address.name,recv_phone=address.phone,recv_province=address.province_name,recv_city=address.city_name,
                         recv_area=address.area_name,recv_address=address.address,total_price=totalprice,order_time=utc_time,status=0)
    # 添加商品
    for i in lst:
        cart=CartModel.query.filter_by(cid=i).first()
        book=BookModel.query.filter_by(bookid=cart.pid).first()
        bookinfo=BookInfoModel.query.filter_by(bookid=cart.pid).first()
        new_item=OrderItemModel(pid=cart.pid,title=book.bookname+"-"+bookinfo.bookauthor+"-"+book.booksort,price=cart.price,num=cart.num)
        new_order.orderitem.append(new_item)
    db.session.add(new_order)
    db.session.commit()
    data={'uid':userid,'recv_name':address.name,'recv_phone':address.phone,'recv_province':address.province_name,'recv_city':address.city_name,
          'recv_area':address.area_name,'recv_address':address.address,'total_price':totalprice,'order_time':utc_time,'oid':new_order.oid}
    return jsonify({'state':'200','data':data})

@bp.route("/selectorder/<id>")
def selectorder(id):
    print(id)
    order = OrderModel.query.filter_by(oid=id).first()
    data={'total_price':order.total_price,'order_time':order.order_time,'recv_name':order.recv_name,'oid':id}
    return jsonify({'state':'200','data':data})

# 修改订单为未发货
@bp.route("/payment/<oid>",methods=['POST'])
def payment1(oid):
    print(oid)
    order=OrderModel.query.filter_by(oid=oid).first()
    order.status=1
    db.session.commit()
    return jsonify({'state':'200'})

# 显示所有订单
@bp.route("/orders/order",methods=['POST'])
def showorder():
    userid = session.get('user_id')
    orders=OrderModel.query.filter_by(uid=userid).order_by(OrderModel.order_time.desc()).all()
    list=[]
    content={}
    for order in orders:
        content={'oid':order.oid,'uid':order.uid,'recv_name':order.recv_name,'recv_phone':order.recv_phone,'recv_province':order.recv_province,'recv_city':order.recv_city,
                 'recv_area':order.recv_area,'recv_address':order.recv_address,'total_price':order.total_price,'order_time':order.order_time,'status':order.status}
        list.append(content)
        content={}
    return jsonify({'state':'200','data':list})

def showorderitem2(oid):
    orderItems=OrderItemModel.query.filter_by(oid=oid).all()
    list = []
    content = {}
    for orderItem in orderItems:
        content={'id':orderItem.id,'oid':orderItem.oid,'pid':orderItem.pid,'title':orderItem.title,'price':orderItem.price,'num':orderItem.num}
        list.append(content)
        content={}
    return list

# 根据status查询订单和商品
@bp.route("/orders/status/<status>",methods=['POST'])
def orderbystatus2(status):
    print(status)
    userid = session.get('user_id')
    if int(status)==(-1):
        print("hello")
        orders = OrderModel.query.filter_by(uid=userid).order_by(OrderModel.order_time.desc()).all()
    else:
        orders = OrderModel.query.filter_by(uid=userid, status=status).order_by(OrderModel.order_time.desc()).all()
    list = []
    content = {}
    for order in orders:
        content = {'oid': order.oid, 'uid': order.uid, 'recv_name': order.recv_name, 'recv_phone': order.recv_phone,
                   'recv_province': order.recv_province, 'recv_city': order.recv_city,
                   'recv_area': order.recv_area, 'recv_address': order.recv_address, 'total_price': order.total_price,
                   'order_time': order.order_time, 'status': order.status,'orderItem':showorderitem2(order.oid)}
        list.append(content)
        content = {}
    return jsonify({'state': '200', 'data': list})

# 评价商品页面
@bp.route("/comment")
def comment():
    oid=request.args.get("oid")
    print(oid)
    orderitem=OrderItemModel.query.filter_by(oid=oid).first()
    data={'oid':oid,'name':orderitem.title.split('-')[0],'author':orderitem.title.split('-')[1],'type':orderitem.title.split('-')[2]}
    print(data)
    return render_template("Cart/comment.html",orderitem=data)

# 发表评论
@bp.route("/write/comment")
def writecomment():
    userid = session.get('user_id')
    oid=request.args.get('oid')
    comment=request.args.get('comment')
    star=request.args.get('star')
    tags=request.args.get('tags')
    comments=comment+"-"+tags
    print(comment)
    print(star)
    orderitem = OrderItemModel.query.filter_by(oid=oid).first()
    pid=orderitem.pid
    local_time = datetime.now()
    utc_time = local_time.replace(tzinfo=pytz.timezone('UTC')).astimezone(pytz.UTC)
    comment=CommentModel(studentID=userid,bookid=pid,content=comments,commentDate=utc_time,star=star)
    db.session.add(comment)
    db.session.commit()

    order = OrderModel.query.filter_by(oid=oid).first()
    order.status = 4
    db.session.commit()
    return jsonify({'state':'200','msg':"评价成功！"})

# 收藏商品
@bp.route("/shoucang/add",methods=['POST'])
def shoucang1():
    userid = session.get('user_id')
    data=request.get_json()
    bookid=data['bookid']
    title=data['title']
    price=data['price']
    shoucang=ShouCangModel(uid=userid,bookid=bookid,title=title,price=price)
    db.session.add(shoucang)
    db.session.commit()
    return jsonify({'state':'200'})

# 收藏列表
@bp.route("/shoucang/list")
def shoucanglist():
    userid = session.get('user_id')
    pageNum = request.args.get("pageNum", default=1)
    pageSize = request.args.get("pageSize", default=10)
    booklists = {}
    booklist = []
    content = {}
    shoucangs=db.session.query(ShouCangModel.id,ShouCangModel.uid,ShouCangModel.bookid,ShouCangModel.title,ShouCangModel.price).filter_by(uid=userid)
    count = db.session.query(ShouCangModel).filter_by(uid=userid).count()
    if count%pageSize==0:
        sum=count/pageSize
    else:
        sum=count/pageSize+1
    print(count/pageSize)
    page_objs = shoucangs.paginate(
        page=int(pageNum),
        per_page=int(pageSize),
        error_out=False,
        max_per_page=50,
    ).items
    print(count)
    print(page_objs)
    for result in page_objs:
        print(result)
        content = {'id': result[0], 'uid': result[1],'bookid':result[2],'title':result[3],'price':result[4]}
        booklist.append(content)
        content = {}
    booklists = {'list': booklist, 'page': (int)(sum)}
    print(booklists)
    return jsonify(booklists)

# 取消收藏
@bp.route("/shoucang/delete/<id>",methods=['POST'])
def shoucang(id):
    print(id)
    userid = session.get('user_id')
    shoucang=ShouCangModel.query.filter_by(id=id,uid=userid).first()
    db.session.delete(shoucang)
    db.session.commit()
    return jsonify({'state':'200'})

# 收藏加入购物车
@bp.route("/shocuang/addcart/<pid>",methods=['POST'])
def addcare(pid):
    cid=0
    userid = session.get('user_id')
    goods = CartModel.query.filter_by(uid=userid, pid=pid).first()
    if goods:
        cnt = goods.num + 1
        goods.num = cnt
        db.session.commit()
        return jsonify({'state': '300', 'data': cid})
    else:
        bookinfo = BookInfoModel.query.filter_by(bookid=pid).first()
        price = bookinfo.bookprice
        insertCare = CartModel(uid=userid, pid=pid, price=price, num=1)
        db.session.add(insertCare)
        db.session.commit()
        cid = insertCare.cid
        return jsonify({'state': '200', 'data': cid})

# 搜索框查询图书
@bp.route("/search/book",methods=['GET'])
def searchbook():
    txt=request.args.get("bookname")
    print(txt)
    pageNum = request.args.get("pageNum", default=1)
    pageSize = request.args.get("pageSize", default=10)
    booklists = {}
    booklist = []
    content = {}
    books = db.session.query(BookModel.bookid, BookModel.bookname).filter(or_(BookModel.bookname.like(f"%{txt}%")))
    count = db.session.query(BookModel).filter(or_(BookModel.bookname.like(f"%{txt}%"))).count()
    if count % pageSize == 0:
        sum = count / pageSize
    else:
        sum = count / pageSize + 1
    print(count / pageSize)
    # 分页查询
    page_objs = books.paginate(
        page=int(pageNum),
        per_page=int(pageSize),
        error_out=False,
        max_per_page=50,
    ).items
    print(count)
    print(page_objs)
    for result in page_objs:
        content = {'bookid': result[0], 'bookname': result[1]}
        booklist.append(content)
        content = {}
    booklists = {'list': booklist, 'page': (int)(sum)}
    print(booklists)
    return jsonify(booklists)